package pers.cz.netty.handle;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.cz.netty.protocal.Message;
import pers.cz.netty.protocal.MsgType;
import pers.cz.netty.protocal.PongMsg;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: PostGirl-panent
 * @description: 服务端心跳实现
 * @author: Cheng Zhi
 * @create: 2022-10-05 08:13
 **/
@ChannelHandler.Sharable
public class ServerHeartBeatHandler extends SimpleChannelInboundHandler<Message> {

    private static final Logger log = LoggerFactory.getLogger(ServerHeartBeatHandler.class);

    public AtomicInteger onLineCount = new AtomicInteger(0);
    /**
     * 接收到消息时触发
     * @param channelHandlerContext
     * @param message
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Message message) throws Exception {
        Message msg = (Message) message;
        if (MsgType.PING == msg.getMsgType() || MsgType.PONG == msg.getMsgType()) {
            log.debug("Client message： type：{}, body length：{}, body：{}", msg.getMsgType(), msg.getContentLength(), msg.getContent());
            Message pongMsg = new PongMsg();
            channelHandlerContext.writeAndFlush(pongMsg);
        } else {
            channelHandlerContext.fireChannelRead(msg);
        }
    }

    /**
     * 建立连接时触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        int andIncrement = onLineCount.incrementAndGet(); // 自增
        if (log.isDebugEnabled()) {
            log.debug("客户端连接，当前在线客户端共：" + andIncrement);
        }
        super.channelActive(ctx);
    }

    /**
     * 断开连接时触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        int andIncrement = onLineCount.decrementAndGet(); // 自减
        if (log.isDebugEnabled()) {
            log.debug("客户端退出，当前在线客户端共：" + andIncrement);
        }
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("服务器读取数据异常");
        super.exceptionCaught(ctx, cause);
        Channel channel = ctx.channel();
        if(channel.isActive()) {
            ctx.close();
        }
    }
}
